package com.murong.ai.chat.domain.text2speech.xfyun;

import cn.xfyun.api.TtsClient;
import com.murong.ai.chat.domain.text2speech.TTSService;
import lombok.SneakyThrows;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.autoconfigure.condition.ConditionalOnProperty;
import org.springframework.core.env.Environment;
import org.springframework.core.io.ResourceLoader;
import org.springframework.scheduling.annotation.Async;
import org.springframework.stereotype.Service;

import javax.sound.sampled.TargetDataLine;

@Service
@ConditionalOnProperty(name = "tts.call.service", havingValue = "xfyun", matchIfMissing = false)
public class XfYunTTSService implements TTSService<TTsWebSocketListener> {
    private String appId;
    private String apiSecret;
    private String apiKey;
    private String vcn;

    @SneakyThrows
    public XfYunTTSService(Environment environment, ResourceLoader resourceLoader){
        appId=environment.getProperty("tts.xfyun.appid");
        apiSecret=environment.getProperty("tts.xfyun.apisecret");
        apiKey=environment.getProperty("tts.xfyun.apikey");
        vcn=environment.getProperty("tts.xfyun.vcn");
    }

    @SneakyThrows
    @Override
    public void execute(String text) {
        TtsClient ttsClient = new TtsClient.Builder()
                .signature(appId, apiKey, apiSecret).vcn(vcn).aue("raw")
                .build();
        try {
            ttsClient.send(text, new TTsWebSocketListener());
        }catch (Exception e){
            System.out.println(e.getMessage());
            System.out.println("错误码查询链接：https://www.xfyun.cn/document/error-code");
        }
    }

    @Async
    @SneakyThrows
    @Override
    public TTsWebSocketListener asynTextToSpeech(String text) {
        TtsClient ttsClient = new TtsClient.Builder()
                .signature(appId, apiKey, apiSecret).vcn(vcn).aue("raw")
                .build();
        TTsWebSocketListener tTsListener=null;
        try {
            tTsListener = new TTsWebSocketListener(text);
            ttsClient.send(text, tTsListener);
        }catch (Exception e){
            System.out.println(e.getMessage());
            System.out.println("错误码查询链接：https://www.xfyun.cn/document/error-code");
        }
        return tTsListener;
    }

    public void stopRunning(TTsWebSocketListener tTsListener) {
        tTsListener.stopRuning();
    }
}
